﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using MF.Data;

namespace MF.ServiceModel
{
    public sealed class WcfDbContextManager<TContext> : IDbContextManager
        where TContext : IDbContext, new()
    {
        public IDbContext GetDbContext()
        {
            return this.GetOrCreateDbContext();
        }

        private IDbContext GetOrCreateDbContext()
        {
            var ctxInstanceExtension = OperationContext.Current
                                                       .InstanceContext
                                                       .Extensions
                                                       .Find<DbContextInstanceExtension>();
            if (ctxInstanceExtension == null)
            {
                //the service has no DbContextInstanceExtensions, so a new TContext is returned
                return new TContext();
            }

            if (ctxInstanceExtension.Context == null)
                ctxInstanceExtension.Context = new TContext();

            return ctxInstanceExtension.Context;
        }
    }
}
